package com.silence.whereeat.splash;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;

import com.silence.whereeat.R;
import com.silence.whereeat.login.LoginActivity;
import com.silence.whereeat.main.MainActivity;
import com.silence.whereeat.model.UserInfo;
import com.silence.whereeat.utils.CommonUrl;
import com.silence.whereeat.utils.Content;
import com.silence.whereeat.utils.HttpClientPost;

public class SplashActivity extends Activity {
    TextView versiontv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.setContentView(R.layout.splash);
        versiontv = (TextView) findViewById(R.id.versiontv);
        versiontv.setText(getVersion());
        SharedPreferences sharedPreferences = this.getSharedPreferences("userInfo", Context.MODE_PRIVATE);
        if (isNetWorkConn()) {
            if (sharedPreferences.getBoolean("ISCHECK", false)) {
                String username = sharedPreferences.getString("USERNAME", "");
                String password = sharedPreferences.getString("PASSWORD", "");
                UserInfo userInfo = new UserInfo(username, password);
                new Handler().postAtTime(new loadToMainActivity(userInfo), SystemClock.uptimeMillis() + 2000);
            } else {
                new Handler().postAtTime(new loadToLoginActivity(), SystemClock.uptimeMillis() + 2000);
            }
        } else {
            showAlertDialog();
        }
    }

    /**
     * 获取版本号
     *
     * @return
     */
    private String getVersion() {
        String version = "Version";
        try {
            PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), 0);
            version += info.versionName;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return version;
    }

    /**
     * 检测网络是否连接
     *
     * @return
     */
    private boolean isNetWorkConn() {
        ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
        NetworkInfo info = manager.getActiveNetworkInfo();
        return info != null && info.isConnected();
    }

    /**
     * 用于开启等待线程跳转主页面
     */
    class loadToLoginActivity implements Runnable {

        @Override
        public void run() {
            Intent intent = new Intent();
            intent.setClass(getApplicationContext(), LoginActivity.class);
            startActivity(intent);
            finish();
        }
    }

    /**
     * 用于判断登陆状态
     */
    public class loadToMainActivity implements Runnable {
        UserInfo userInfo;

        public loadToMainActivity(UserInfo userInfo) {
            this.userInfo = userInfo;
        }

        @Override
        public void run() {
            new AsyncTask<UserInfo, Void, String>() {
                @Override
                protected String doInBackground(UserInfo... params) {
                    HttpClientPost httpClientPost = new HttpClientPost(CommonUrl.URL_LOGIN);
                    return httpClientPost.getLoginResult(params[0]);
                }

                @Override
                protected void onPostExecute(String result) {
                    if (result.equals(Content.STR_SUCCESS)) {
                        Intent intent = new Intent(SplashActivity.this, MainActivity.class);
                        startActivity(intent);
                        finish();
                    } else {
                        Intent intent = new Intent(SplashActivity.this, LoginActivity.class);
                        startActivity(intent);
                        Toast.makeText(SplashActivity.this, "自动登陆失败,请手动登陆!", Toast.LENGTH_SHORT).show();
                        finish();
                    }
                }
            }.execute(userInfo);
        }
    }

    public void showAlertDialog() {
        AlertDialog.Builder builder = new Builder(this);
        builder.setTitle("设置网络");
        builder.setMessage("网络无法连接请前往设置");
        builder.setPositiveButton("设置网络", new OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                Intent intent = new Intent();
                intent.setClassName("com.android.settings", "com.android.settings.Settings");//com.android.settings/.Settings
                startActivity(intent);
                finish();
            }
        });
        builder.setNegativeButton("退出", new OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });
        builder.create().show();
    }

}
